//
//  ViewController.swift
//  AMICTR
//
//  Created by QFX on 2023/11/22.
//

import UIKit
import SnapKit
import SGSelectionModal
import SwiftRadix
import CoreBluetooth

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    var languageType:LanguageType = .english
    @IBOutlet weak var languageButton: UIButton!
    @IBOutlet weak var selectMictrButton: UIButton!
    @IBOutlet weak var dateButton: UIButton!
    @IBOutlet weak var timeButton: UIButton!
    @IBOutlet weak var utcsButton: UIButton!
    @IBOutlet weak var displaymodeButton: UIButton!
    @IBOutlet weak var cityTimeButton: UIButton!
    @IBOutlet weak var volumeButton: UIButton!
    @IBOutlet weak var sunlightstartButton: UIButton!
    @IBOutlet weak var sunlightendButton: UIButton!
    @IBOutlet weak var alarmNameButton: UIButton!
    @IBOutlet weak var singleAlarmNameButton: UIButton!
    @IBOutlet weak var dateNameButton: UIButton!
    @IBOutlet weak var timeNameButton: UIButton!
    @IBOutlet weak var utcsNameButton: UIButton!
    @IBOutlet weak var sunlightstartNameButton: UIButton!
    @IBOutlet weak var sunlightendNameButton: UIButton!
    @IBOutlet weak var volumeNameButton: UIButton!
    @IBOutlet weak var cityTimeNameButton: UIButton!
    @IBOutlet weak var displaymodeNameButton: UIButton!
    
    @IBOutlet weak var singleAlarmNameLabel: UILabel!
    @IBOutlet weak var alarmNameLabel: UILabel!
    @IBOutlet weak var dateTimeSendButtton: UIButton!
    @IBOutlet weak var sunlightSendButton: UIButton!
    @IBOutlet weak var displaymodeSendButton: UIButton!
    @IBOutlet weak var cityTimeSendButton: UIButton!
    @IBOutlet weak var volumeSendButton: UIButton!
    @IBOutlet weak var utcsSendButton: UIButton!
    @IBOutlet weak var alarmsSendButton: UIButton!
    @IBOutlet weak var singleAlarmSendButton: UIButton!
    @IBOutlet weak var alarmTimeButton: UIButton!
    @IBOutlet weak var singleAlarmTimeButton: UIButton!
    
    @IBOutlet weak var revolutionButton: UIButton!
    @IBOutlet weak var circleButton: UIButton!
    @IBOutlet weak var rotationButton: UIButton!
    
    @IBOutlet weak var revolutionNameButton: UIButton!
    @IBOutlet weak var rotationNameButton: UIButton!
    @IBOutlet weak var circleNameButton: UIButton!
    
    @IBOutlet weak var revolutionSendButton: UIButton!
    @IBOutlet weak var circleSendButton: UIButton!
    @IBOutlet weak var rotationSendButton: UIButton!
    
    var languages:[String] = ["English","中文","日本語"]
    var UTCs:[String] = ["UTC0","UTC+1","UTC+2","UTC+3","UTC+4","UTC+5","UTC+6","UTC+7","UTC+8","UTC+9","UTC+10","UTC+11","UTC12","UTC-11","UTC-10","UTC-9","UTC-8","UTC-7","UTC-6","UTC-5","UTC-4","UTC-3","UTC-2","UTC-1"]
    var sunlightStarts:[String] = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"]
    var sunlightEnds:[String] = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"]
    var volums:[String] = ["1","2","3","4","5","6","7","0"]
    var cityTimes:[String] = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"]
    var displayMode:[String] = ["1","2","3" ]
    var alarms:[String] = ["ON","OFF"]
    var singleAlarms:[String] = ["ON","OFF"]
    var revolutions:[String] = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"]
    var circles:[String] = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"]
    var rotations:[String] = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"]

    var languageIndex:Int = 0
    var utcIndex:Int = 0
    var sunlightStartIndex:Int = 0
    var sunlightEndIndex:Int = 0
    var volumIndex:Int = 0
    var cityTimeIndex:Int = 0
    var displayModeIndex:Int = 0
    var scanDevices = [OBDBluetoothPeripheral]()
    var scanDeviceSelectIndex:Int = 0
    var alarmSelectIndex:Int = 0
    var singleAlarmSelectIndex:Int = 0

    var revolutionSelectIndex:Int = 0
    var circleSelectIndex:Int = 0
    var rotationSelectIndex:Int = 0

    
    var year:Int?
    var month:Int?
    var day:Int?

    var hour:Int?
    var minute:Int?
    
    var alarmHour:Int?
    var alarmMinute:Int?
    
    var singleAlarmHour:Int?
    var singleAlarmMinute:Int?
    
    var isBlueConnected:Bool = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        ODBBLEManager.scan(withDuration: 3, completionHandler:  { peripherals, error in
            if let devices = peripherals{
                self.scanDevices = devices
                self.selectMictrConnect(UIButton())
             }
        })
    }
    
    @IBAction func languageSet(_ sender: Any) {
        self.showSectionsModal(title: "Languages", data: self.languages,selectIndex: self.languageIndex) { index in
            self.languageIndex = index
            self.languageButton.setTitle(self.languages[index], for: .normal)
            self.languageType = index == 0 ? .english : index == 1 ? .chinese : .jp
            self.setUpdateUI()
        }
    }
    
    
    @IBAction func singleAlarmOpen(_ sender: Any) {
        self.showSectionsModal(title: self.singleAlarmNameButton.titleLabel?.text ?? "", data: self.singleAlarms,selectIndex: self.singleAlarmSelectIndex) { index in
            self.singleAlarmSelectIndex = index
            self.singleAlarmNameButton.setTitle(self.singleAlarms[index], for: .normal)
        }
    }
   
    @IBAction func alarmOpen(_ sender: Any) {
        self.showSectionsModal(title: self.alarmNameButton.titleLabel?.text ?? "", data: self.alarms,selectIndex: self.alarmSelectIndex) { index in
            self.alarmSelectIndex = index
            self.alarmNameButton.setTitle(self.alarms[index], for: .normal)
        }
    }
    @IBAction func alarmTimeSelectUp(_ sender: Any) {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: Int(UIScreen.main.bounds.height)))
        view.backgroundColor = UIColor(white: 0, alpha: 0.5)
        let dateView:DateTimePickerView2 = DateTimePickerView2.init(frame: CGRect.zero)
        view.addSubview(dateView)
        UIApplication.shared.keyWindow?.addSubview(view)
        dateView.backgroundColor = .white
        dateView.title.text = self.timeNameButton.titleLabel?.text
        if self.languageType == .english {
            dateView.cancelButton.setTitle("Cancel", for: .normal)
            dateView.confirmButton.setTitle("Confirm", for: .normal)
         }else if self.languageType == .chinese {
             dateView.cancelButton.setTitle("取消", for: .normal)
             dateView.confirmButton.setTitle("确定", for: .normal)
        }else{
            dateView.cancelButton.setTitle("キャンセル", for: .normal)
            dateView.confirmButton.setTitle("を選択して、", for: .normal)
        }
        let nowDate = CommonHelper.date2String(Date(),dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.initData(dateString: nowDate,dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.canButtonReturnB = {
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.sucessReturnB = { datestring in
            let time = datestring.split(separator: ":")
            if (time.count > 0){
                self.alarmHour = "\(time[0])".toInt()
                self.alarmMinute = "\(time[1])".toInt()
             }
            self.alarmTimeButton.setTitle(datestring, for: .normal)
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(300)
        }
    }
    
    @IBAction func singleAlarmTimeSelectUp(_ sender: Any) {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: Int(UIScreen.main.bounds.height)))
        view.backgroundColor = UIColor(white: 0, alpha: 0.5)
        let dateView:DateTimePickerView2 = DateTimePickerView2.init(frame: CGRect.zero)
        view.addSubview(dateView)
        UIApplication.shared.keyWindow?.addSubview(view)
        dateView.backgroundColor = .white
        dateView.title.text = self.timeNameButton.titleLabel?.text
        if self.languageType == .english {
            dateView.cancelButton.setTitle("Cancel", for: .normal)
            dateView.confirmButton.setTitle("Confirm", for: .normal)
         }else if self.languageType == .chinese {
             dateView.cancelButton.setTitle("取消", for: .normal)
             dateView.confirmButton.setTitle("确定", for: .normal)
        }else{
            dateView.cancelButton.setTitle("キャンセル", for: .normal)
            dateView.confirmButton.setTitle("を選択して、", for: .normal)
        }
        let nowDate = CommonHelper.date2String(Date(),dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.initData(dateString: nowDate,dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.canButtonReturnB = {
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.sucessReturnB = { datestring in
            let time = datestring.split(separator: ":")
            if (time.count > 0){
                self.singleAlarmHour = "\(time[0])".toInt()
                self.singleAlarmMinute = "\(time[1])".toInt()
            }
            self.singleAlarmTimeButton.setTitle(datestring, for: .normal)
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(300)
        }
    }
    
    @IBAction func timeSelectUp(_ sender: Any) {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: Int(UIScreen.main.bounds.height)))
        view.backgroundColor = UIColor(white: 0, alpha: 0.5)
        let dateView:DateTimePickerView2 = DateTimePickerView2.init(frame: CGRect.zero)
        view.addSubview(dateView)
        UIApplication.shared.keyWindow?.addSubview(view)
        dateView.backgroundColor = .white
        dateView.title.text = self.timeNameButton.titleLabel?.text
        if self.languageType == .english {
            dateView.cancelButton.setTitle("Cancel", for: .normal)
            dateView.confirmButton.setTitle("Confirm", for: .normal)
         }else if self.languageType == .chinese {
             dateView.cancelButton.setTitle("取消", for: .normal)
             dateView.confirmButton.setTitle("确定", for: .normal)
        }else{
            dateView.cancelButton.setTitle("キャンセル", for: .normal)
            dateView.confirmButton.setTitle("を選択して、", for: .normal)
        }
        let nowDate = CommonHelper.date2String(Date(),dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.initData(dateString: nowDate,dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.canButtonReturnB = {
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.sucessReturnB = { datestring in
            let time = datestring.split(separator: ":")
            if (time.count > 0){
                self.hour = "\(time[0])".toInt()
                self.minute = "\(time[1])".toInt()
             }
            self.timeButton.setTitle(datestring, for: .normal)
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(300)
        }
    }

    
    @IBAction func dateSelectUp(_ sender: Any) {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: Int(UIScreen.main.bounds.height)))
        view.backgroundColor = UIColor(white: 0, alpha: 0.5)
        let dateView:DateTimePickerView = DateTimePickerView.init(frame: CGRect.zero)
        view.addSubview(dateView)
        UIApplication.shared.keyWindow?.addSubview(view)
        dateView.backgroundColor = .white
        dateView.title.text = self.dateNameButton.titleLabel?.text
        if self.languageType == .english {
            dateView.cancelButton.setTitle("Cancel", for: .normal)
            dateView.confirmButton.setTitle("Confirm", for: .normal)
         }else if self.languageType == .chinese {
             dateView.cancelButton.setTitle("取消", for: .normal)
             dateView.confirmButton.setTitle("确定", for: .normal)
        }else{
            dateView.cancelButton.setTitle("キャンセル", for: .normal)
            dateView.confirmButton.setTitle("を選択して、", for: .normal)
        }
        let nowDate = CommonHelper.date2String(Date(),dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.initData(dateString: nowDate,dateFormat: "yyyy-MM-dd HH:mm:ss")
        dateView.canButtonReturnB = {
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.sucessReturnB = { datestring in
            let yearMonthDayArray = datestring.split(separator: "-")
            if (yearMonthDayArray.count > 0){
                self.year = "\(yearMonthDayArray[0])".toInt()
                self.month = "\(yearMonthDayArray[1])".toInt()
                self.day = "\(yearMonthDayArray[2])".toInt()

                let yearMonthDay = "\(yearMonthDayArray[1])-\(yearMonthDayArray[2])-\(yearMonthDayArray[0])"
                self.dateButton.setTitle(yearMonthDay, for: .normal)
            }
            dateView.snp.remakeConstraints { make in
                make.bottom.equalTo(-400)
                make.height.equalTo(300)
                make.left.right.equalToSuperview()
            }
            dateView.removeFromSuperview()
            view.removeFromSuperview()
        }
        dateView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(300)
        }
    }

    @IBAction func UTCSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.utcsNameButton.titleLabel?.text ?? "", data: self.UTCs,selectIndex: self.utcIndex) { index in
            self.utcIndex = index
            self.utcsButton.setTitle(self.UTCs[index], for: .normal)
        }
    }
    
    @IBAction func SunlightStartSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.sunlightstartNameButton.titleLabel?.text ?? "", data: self.sunlightStarts,selectIndex: self.sunlightStartIndex) { index in
            self.sunlightStartIndex = index
            self.sunlightstartButton.setTitle(self.sunlightStarts[index], for: .normal)
        }
    }
    
    @IBAction func SunlightEndSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.sunlightendNameButton.titleLabel?.text ?? "", data: self.sunlightEnds,selectIndex: self.sunlightEndIndex) { index in
            self.sunlightEndIndex = index
            self.sunlightendButton.setTitle(self.sunlightEnds[index], for: .normal)
        }
    }
    
    @IBAction func VolumeSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.volumeNameButton.titleLabel?.text ?? "", data: self.volums,selectIndex: self.volumIndex) { index in
            self.volumIndex = index
            self.volumeButton.setTitle(self.volums[index], for: .normal)
        }
    }
    
    
    @IBAction func CityTimeSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.cityTimeNameButton.titleLabel?.text ?? "", data: self.cityTimes,selectIndex: self.cityTimeIndex) { index in
            self.cityTimeIndex = index
            self.cityTimeButton.setTitle(self.cityTimes[index], for: .normal)

        }
    }
    
    @IBAction func DisplayModeSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.displaymodeNameButton.titleLabel?.text ?? "", data: self.displayMode,selectIndex: self.displayModeIndex) { index in
            self.displayModeIndex = index
            self.displaymodeButton.setTitle(self.displayMode[index], for: .normal)
        }
    }
    
    
    @IBAction func CircleSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.circleNameButton.titleLabel?.text ?? "", data: self.circles,selectIndex: self.circleSelectIndex) { index in
            self.circleSelectIndex = index
            self.circleButton.setTitle(self.circles[index], for: .normal)
        }
    }
    
    @IBAction func RevolutionSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.revolutionNameButton.titleLabel?.text ?? "", data: self.revolutions,selectIndex: self.revolutionSelectIndex) { index in
            self.revolutionSelectIndex = index
            self.revolutionButton.setTitle(self.revolutions[index], for: .normal)
        }
    }
    
    
    @IBAction func RotationSelectUp(_ sender: Any) {
        self.showSectionsModal(title: self.rotationNameButton.titleLabel?.text ?? "", data: self.rotations,selectIndex: self.rotationSelectIndex) { index in
            self.rotationSelectIndex = index
            self.rotationButton.setTitle(self.rotations[index], for: .normal)
        }
    }
    /**
     同时发送：224、231、255
     */
    @IBAction func selectMictrConnect(_ sender: Any) {
        var data:[String] = []
        if self.scanDevices.count > 0 {
            for var device in self.scanDevices{
                let peripheralName = device.peripheralName
                if peripheralName.count > 0{
                    data.append(peripheralName)
                }
            }
        }
        if (data.count > 0){
            self.showSectionsModal(title: self.selectMictrButton.titleLabel?.text ?? "", data: data,selectIndex: self.scanDeviceSelectIndex,closeTitle: "Connect") { index in
                self.scanDeviceSelectIndex = index
                /// 224、231、255
                ///0xE0、0xE7、0xFF 同时发送
                let per = self.scanDevices[self.scanDeviceSelectIndex]
                if per.peripheralName == ODBBLEManager.centralManager.currentPeripheral?.peripheralName {
                    self.isBlueConnected = true
                    if self.languageType == .english {
                        self.selectMictrButton.setTitle("Successful connected", for: .normal)
                     }else if self.languageType == .chinese {
                        self.selectMictrButton.setTitle("MICTR连接成功", for: .normal)
                    }else{
                        self.selectMictrButton.setTitle("MICTR接続成功", for: .normal)
                    }
                    return
                }
                ODBBLEManager.connect(peripheral: per, completionHandler:  { peripheral, res in
                    if peripheral != nil {
                        self.isBlueConnected = true
                        if self.languageType == .english {
                            self.selectMictrButton.setTitle("Successful connected", for: .normal)
                         }else if self.languageType == .chinese {
                            self.selectMictrButton.setTitle("MICTR连接成功", for: .normal)
                        }else{
                            self.selectMictrButton.setTitle("MICTR接続成功", for: .normal)
                        }
                        let commanData = "E0E7FF".hexaData
                        print("发送数据：\(commanData)")
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                                if let characteristicWrite = per.characteristicWrite {
                                    per.peripheral.writeValue(commanData, for: characteristicWrite, type: .withResponse)
                                }else {
                                    print("发送数据出现错误")
                                }
                            }
                        }
                    }
                })
            }
        }
    }
    
    
    /**
     按日期、时间发送键发送：224、167、双字节“年度”、“月份”、“日期”、“小时”、“分钟”、255.
     */
    @IBAction func dateTimeSend(_ sender: Any) {
        /// 224、167
        ///日期：0xE0、0xA7
        if let year = self.year,let month = self.month,let day = self.day, let hour = self.hour,let minute = self.minute {
            let data = year
            let lsb = data & 0xFF
            let msb = (data >> 8) & 0xFF
            let yearHex = String(format: "%02x%02x", lsb, msb).uppercased()
            let monthHex = self.creatIntToHex(hex: month)
            let dayHex = self.creatIntToHex(hex: day)
            let hourHex = self.creatIntToHex(hex: hour)
            let miuteHex = self.creatIntToHex(hex: minute)
            let commonHex = "E0A7"+yearHex+monthHex+dayHex+hourHex+miuteHex+"FF"
            print(commonHex)
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
     }
    /**
     按时区发送键发送：224、168、E0A8
     如果时区下拉框元素是UTC0,发送0、
     如果时区下拉框元素是UTC+1发送1、
     如果时区下拉框元素是UTC+2,发送2、
     如果时区下拉框元素是UTC+3,发送3、
     如果时区下拉框元素是UTC+4,发送4、
     如果时区下拉框元素是UTC+5,发送5、
     如果时区下拉框元素是UTC+6,发送6、
     如果时区下拉框元素是UTC+7,发送7、
     如果时区下拉框元素是UTC+8,发送8、
     如果时区下拉框元素是UTC+9,发送9、
     如果时区下拉框元素是UTC+10,发送10、
     如果时区下拉框元素是UTC+11,发送11、
     如果时区下拉框元素是UTC12,发送12、
     如果时区下拉框元素是UTC-1,发送23、
     如果时区下拉框元素是UTC-2,发送22、
     如果时区下拉框元素是UTC-3,发送21、
     如果时区下拉框元素是UTC-4,发送20、
     如果时区下拉框元素是UTC-5,发送19、
     如果时区下拉框元素是UTC-6,发送18、
     如果时区下拉框元素是UTC-7,发送17、
     如果时区下拉框元素是UTC-8,发送16、
     如果时区下拉框元素是UTC-9,发送15、
     如果时区下拉框元素是UTC-10,发送14、
     如果时区下拉框元素是UTC-11,发送13、
     ["UTC0","UTC+1","UTC+2","UTC+3","UTC+4","UTC+5","UTC+6","UTC+7","UTC+8","UTC+9","UTC+10","UTC+11","UTC12","UTC-11","UTC-10","UTC-9","UTC-8","UTC-7","UTC-6","UTC-5","UTC-4","UTC-3","UTC-2","UTC-1"]
     255.
     */
    
    @IBAction func UTCSend(_ sender: Any) {
        var command = self.utcIndex
        let commandEx = self.creatIntToHex(hex: command)
        let commonHex = "E0A8"+commandEx+"FF"
        print(commonHex)
        if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
            if let characteristicWrite = per.characteristicWrite {
                per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
            }else {
                print("发送数据出现错误")
            }
        }
    }
    
    /**
     太阳光开始下拉框元素：6,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
     太阳光结束下拉框元素：22,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
     按太阳光时间发送键发送：224、227、太阳光开始下拉框选中项、太阳光结束下拉框选中项、255
     0XE0E3
     */
    @IBAction func SunlightSend(_ sender: Any) {
        let start = self.sunlightStarts[self.sunlightStartIndex]
        let end  = self.sunlightEnds[self.sunlightEndIndex]
        let startInt = start.toInt()
        let endInt = end.toInt()
        let commandStartEx = creatIntToHex(hex: startInt)
        let commandEndEx = creatIntToHex(hex: endInt)
        let commonHex = "E0E3"+commandStartEx+commandEndEx+"FF"
        print(commonHex)
        if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
            if let characteristicWrite = per.characteristicWrite {
                per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
            }else {
                print("发送数据出现错误")
            }
        }
    }

    
    /**
     音量选择下拉框元素：1,2,3,4,5,6,7,0
     按音量发送键发送：224、230、音量选择下拉框选中值、255
     */
    @IBAction func VolumeSend(_ sender: Any) {
        let volume  = self.volums[self.volumIndex]
        if let hexValue = Int(volume){
            let commonHex = "E0E6" + creatIntToHex(hex:hexValue)+"FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    print(commonHex.hexaData)
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
    }

    /**
     其他城市时间选择下拉框元素：0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
     按其他城市时间发送键发送：224、170、其他城市时间选择下拉框选中值、255
     */
    @IBAction func CityTimeSend(_ sender: Any) {
        let time  = self.cityTimes[self.cityTimeIndex]
        if let hexValue = Int(time){
            let commonHex = "E0AA"+creatIntToHex(hex: hexValue)+"FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    print(commonHex.hexaData)
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
    }
    /**
     按不重复闹钟数据发送：224、173、G3显示框中小时、G3显示框中分、G5下拉框如果选中项是“OFF”发送0；G5下拉框如果是“ON”发送1、255

     */
    @IBAction func singleAlarmSend(_ sender: Any) {
        if let hour = self.singleAlarmHour,
           let minute = self.singleAlarmMinute{
            let commandHourEx = creatIntToHex(hex: hour)
            let commandMinuteEx = creatIntToHex(hex: minute)
            let isOpen = self.singleAlarms[self.singleAlarmSelectIndex]
            let openHex = isOpen == "ON" ? "01" : "00"
            let commanHex = "E0AD"+commandHourEx+commandMinuteEx+openHex+"FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                 if let characteristicWrite = per.characteristicWrite {
                    print(commanHex.hexaData)
                    per.peripheral.writeValue(commanHex.hexaData, for: characteristicWrite, type: .withResponse)
                 }else {
                    print("发送数据出现错误")
                 }
            }
        }
    }
    
    /**
     按周一到周五闹钟数据发送：224、172、G1显示框中小时、G1显示框中分、G7下拉框如果选中项是“OFF”发送0；G7下拉框如果是“ON”发送1、255
     */
    @IBAction func alarmSend(_ sender: Any) {
        if let hour = self.alarmHour,
           let minute = self.alarmMinute {
            let commandHourEx = creatIntToHex(hex: hour)
            let commandMinuteEx = creatIntToHex(hex: minute)
            let isOpen = self.alarms[self.alarmSelectIndex]
            let openHex = isOpen == "ON" ? "01" : "00"
            let commanHex = "E0AC"+commandHourEx+commandMinuteEx+openHex+"FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                 if let characteristicWrite = per.characteristicWrite {
                    print(commanHex.hexaData)
                    per.peripheral.writeValue(commanHex.hexaData, for: characteristicWrite, type: .withResponse)
                 }else {
                    print("发送数据出现错误")
                 }
            }
        }
    }
    /**
     显示发送下拉框元素：1,2
     按显示方式发送键发送：224、171、显示方式下拉框选中项、255
     */
    @IBAction func DisplayModeSend(_ sender: Any) {
        let display  = self.displayMode[self.displayModeIndex]
        if let hexValue = Int(display){
            let commonHex = "E0AB" + creatIntToHex(hex: hexValue) + "FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    print(commonHex.hexaData)
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
    }
    
    /*
     公转调整发送：E0D0公转调整下拉框选中值FF.*/
    @IBAction func RevolutionSend(_ sender: Any) {
        let revolution  = self.revolutions[self.revolutionSelectIndex]
        if let hexValue = Int(revolution){
            let commonHex = "E0D0" + creatIntToHex(hex: hexValue) + "FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    print(commonHex.hexaData)
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
    }
    /**自转调整发送：E0D1自转调整下拉框选中值FF.*/
    @IBAction func RotationSend(_ sender: Any) {
        let rotation  = self.rotations[self.rotationSelectIndex]
        if let hexValue = Int(rotation){
            let commonHex = "E0D1" + creatIntToHex(hex: hexValue) + "FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    print(commonHex.hexaData)
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
    }
    
    /*
     晨昏圈调整发送：E0D2晨昏圈下拉框选中值FF.*/
    @IBAction func CircleSend(_ sender: Any) {
        let circle  = self.circles[self.circleSelectIndex]
        if let hexValue = Int(circle){
            let commonHex = "E0D2" + creatIntToHex(hex: hexValue) + "FF"
            if let per:OBDBluetoothPeripheral = ODBBLEManager.currentConnectPeripheral() {
                if let characteristicWrite = per.characteristicWrite {
                    print(commonHex.hexaData)
                    per.peripheral.writeValue(commonHex.hexaData, for: characteristicWrite, type: .withResponse)
                }else {
                    print("发送数据出现错误")
                }
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.setUpdateUI()
        //添加代理
        ODBBLEManager.addChannel(delegate: self)

        self.dateButton.setTitle("", for: .normal)
        self.timeButton.setTitle("", for: .normal)
        self.languageButton.setTitle("English", for: .normal)
        self.utcsButton.setTitle(self.UTCs[self.utcIndex], for: .normal)
        self.displaymodeButton.setTitle(self.displayMode[self.displayModeIndex], for: .normal)
        self.cityTimeButton.setTitle(self.cityTimes[self.cityTimeIndex], for: .normal)
        self.volumeButton.setTitle(self.volums[self.volumIndex], for: .normal)
        self.sunlightstartButton.setTitle(self.sunlightStarts[self.sunlightStartIndex], for: .normal)
        self.sunlightendButton.setTitle(self.sunlightEnds[self.sunlightEndIndex], for: .normal)
    }
    
    func setUpdateUI(){
        if self.languageType == .english {
            self.dateNameButton.setTitle("Date Selection", for: .normal)
            self.timeNameButton.setTitle("Time Selection", for: .normal)
            self.utcsNameButton.setTitle("Time Zone Selection", for: .normal)
            self.sunlightstartNameButton.setTitle("Sunlight Start", for: .normal)
            self.sunlightendNameButton.setTitle("Sunlight End", for: .normal)
            self.volumeNameButton.setTitle("Volume", for: .normal)
            self.cityTimeNameButton.setTitle("Other City Time", for: .normal)
            self.displaymodeNameButton.setTitle("Display Mode", for: .normal)
            self.dateTimeSendButtton.setTitle("Send", for: .normal)
            self.sunlightSendButton.setTitle("Send", for: .normal)
            self.displaymodeSendButton.setTitle("Send", for: .normal)
            self.cityTimeSendButton.setTitle("Send", for: .normal)
            self.volumeSendButton.setTitle("Send", for: .normal)
            self.utcsSendButton.setTitle("Send", for: .normal)
            self.alarmsSendButton.setTitle("Send", for: .normal)
            self.singleAlarmSendButton.setTitle("Send", for: .normal)
            self.alarmNameLabel.text = "Mon to Fri Alarm"
            self.singleAlarmNameLabel.text = "Single Alarm"
            self.revolutionNameButton.setTitle("Revolution Adj", for: .normal)
            self.circleNameButton.setTitle("Dusk circle Adj", for: .normal)
            self.rotationNameButton.setTitle("Rotation Adj", for: .normal)
            self.revolutionSendButton.setTitle("Send", for: .normal)
            self.circleSendButton.setTitle("Send", for: .normal)
            self.rotationSendButton.setTitle("Send", for: .normal)
         }else if self.languageType == .chinese {
             self.dateNameButton.setTitle("日期选择", for: .normal)
             self.timeNameButton.setTitle("时间选择", for: .normal)
             self.utcsNameButton.setTitle("时区选择", for: .normal)
             self.sunlightstartNameButton.setTitle("阳光开始时间", for: .normal)
             self.sunlightendNameButton.setTitle("阳光结束时间", for: .normal)
             self.volumeNameButton.setTitle("音量调整", for: .normal)
             self.cityTimeNameButton.setTitle("设置另一城市时间", for: .normal)
             self.displaymodeNameButton.setTitle("显示模式", for: .normal)
             self.dateTimeSendButtton.setTitle("发送", for: .normal)
             self.sunlightSendButton.setTitle("发送", for: .normal)
             self.displaymodeSendButton.setTitle("发送", for: .normal)
             self.cityTimeSendButton.setTitle("发送", for: .normal)
             self.volumeSendButton.setTitle("发送", for: .normal)
             self.utcsSendButton.setTitle("发送", for: .normal)
             self.alarmsSendButton.setTitle("发送", for: .normal)
             self.singleAlarmSendButton.setTitle("发送", for: .normal)
             self.alarmNameLabel.text = "周一到五闹钟"
             self.singleAlarmNameLabel.text = "单次闹钟"
             self.revolutionNameButton.setTitle("公转调整", for: .normal)
             self.circleNameButton.setTitle("晨昏圈调整", for: .normal)
             self.rotationNameButton.setTitle("自转调整", for: .normal)
             self.revolutionSendButton.setTitle("发送", for: .normal)
             self.circleSendButton.setTitle("发送", for: .normal)
             self.rotationSendButton.setTitle("发送", for: .normal)
         }else{
            self.dateNameButton.setTitle("日付選択", for: .normal)
            self.timeNameButton.setTitle("時刻選択", for: .normal)
            self.utcsNameButton.setTitle("タイムゾーン選択", for: .normal)
            self.sunlightstartNameButton.setTitle("太陽光開始時刻", for: .normal)
            self.sunlightendNameButton.setTitle("太陽光終了時刻", for: .normal)
            self.volumeNameButton.setTitle("ボリューム調整", for: .normal)
            self.cityTimeNameButton.setTitle("他の都市時刻の設定", for: .normal)
            self.displaymodeNameButton.setTitle("表示モード", for: .normal)
            self.dateTimeSendButtton.setTitle("送信", for: .normal)
            self.sunlightSendButton.setTitle("送信", for: .normal)
            self.displaymodeSendButton.setTitle("送信", for: .normal)
            self.cityTimeSendButton.setTitle("送信", for: .normal)
            self.volumeSendButton.setTitle("送信", for: .normal)
            self.utcsSendButton.setTitle("送信", for: .normal)
            self.alarmsSendButton.setTitle("送信", for: .normal)
            self.singleAlarmSendButton.setTitle("送信", for: .normal)
            self.alarmNameLabel.text = "月曜～金曜アラーム"
            self.singleAlarmNameLabel.text = "シングルタイム・ア"
             self.revolutionNameButton.setTitle("公転の調整", for: .normal)
             self.circleNameButton.setTitle("朝夕線の調整", for: .normal)
             self.rotationNameButton.setTitle("自転の調整", for: .normal)
             self.revolutionSendButton.setTitle("送信", for: .normal)
             self.circleSendButton.setTitle("送信", for: .normal)
             self.rotationSendButton.setTitle("送信", for: .normal)
        }
        if (self.isBlueConnected){
            if self.languageType == .english {
                self.selectMictrButton.setTitle("Successful connected", for: .normal)
            }else if self.languageType == .chinese {
                self.selectMictrButton.setTitle("MICTR连接成功", for: .normal)
            }else{
                self.selectMictrButton.setTitle("MICTR接続成功", for: .normal)
            }
        }else{
            if self.languageType == .english {
                self.selectMictrButton.setTitle("SELECT MICTR", for: .normal)
            }else if self.languageType == .chinese {
                self.selectMictrButton.setTitle("蓝牙选择", for: .normal)
            }else{
                self.selectMictrButton.setTitle("ブルートゥース選択", for: .normal)
            }
        }
    }

    func showSectionsModal(title:String,data:[String],selectIndex:Int,closeTitle:String?="Confirm",completion: @escaping (_ index: Int)-> Void){
        var _closeTitle = closeTitle
        if(closeTitle != "Connect" || closeTitle != "连接"){
            if self.languageType == .english {
                _closeTitle = "Confirm"
            }else if self.languageType == .chinese {
                _closeTitle = "确定"
            }else{
                _closeTitle = "を選択して、"
            }
        }
        let modal = SGModal(title: title, closeButtonTitle: _closeTitle!)
        modal.width = 300
        modal.selectedIndex = selectIndex
        for (index, item) in data.enumerated() {
            modal.addItem(item: item) {
                () in
                completion(index)
            }
        }
        modal.show()
    }
    
    func creatIntToHex(hex:Int)->String{
        return String(format:"%02x", hex).uppercased()
    }


}

extension ViewController: BLEDelegate{
    func tag() -> String {
        return "ViewController"
    }
    

    
    //收到的数据在此处理
    func bluetoothPeripheral(_ peripheral: CBPeripheral?, didReadData data: Data){
        print("收到数据 \(data.toString())")
//        let dataString = data.hex.stringValue
        var dataString = ""
        for byte in data {
            let hexByte = String(format:"%02X", UInt8(byte))
            dataString += hexByte + ""
        }
        
        let startIndex = dataString.startIndex
        let data1 = dataString.substring(with: startIndex ..< dataString.index(dataString.startIndex, offsetBy: 2))
        let data2 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 2) ..< dataString.index(dataString.startIndex, offsetBy: 4))
        let data3 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 4) ..< dataString.index(dataString.startIndex, offsetBy: 6))
        let data4 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 6) ..< dataString.index(dataString.startIndex, offsetBy: 8))
        let data5 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 8) ..< dataString.index(dataString.startIndex, offsetBy: 10))
        let data6 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 10) ..< dataString.index(dataString.startIndex, offsetBy: 12))
        let data7 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 12) ..< dataString.index(dataString.startIndex, offsetBy: 14))
        let data8 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 14) ..< dataString.index(dataString.startIndex, offsetBy: 16))
        let data9 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 16) ..< dataString.index(dataString.startIndex, offsetBy: 18))
        let data10 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 18) ..< dataString.index(dataString.startIndex, offsetBy: 20))
        let data11 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 20) ..< dataString.index(dataString.startIndex, offsetBy: 22))
        let data12 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 22) ..< dataString.index(dataString.startIndex, offsetBy: 24))
        let data13 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 24) ..< dataString.index(dataString.startIndex, offsetBy: 26))
        let data14 = dataString.substring(with: dataString.index(dataString.startIndex, offsetBy: 26) ..< dataString.index(dataString.startIndex, offsetBy: 28))
        print("\(data1.hexToInt),\(data2),\(data3),\(data4),\(data5),\(data6),\(data7),\(data8),\(data9),\(data10),\(data11),\(data12),\(data13),\(data14)")
        
        
        if let intData1 = data1.hexToInt{
            self.sunlightstartButton.setTitle(String(intData1), for: .normal)
            self.sunlightStartIndex = self.sunlightStarts.firstIndex(of: String(intData1)) ?? 0
        }
        
        if let intData2 = data2.hexToInt{
            self.sunlightendButton.setTitle(String(intData2), for: .normal)
            self.sunlightEndIndex = self.sunlightStarts.firstIndex(of: String(intData2)) ?? 0
        }

        if let intData3 = data3.hexToInt{
            self.volumeButton.setTitle(String(intData3), for: .normal)
            self.volumIndex = self.volums.firstIndex(of: String(intData3)) ?? 0
        }
        
        if let intData4 = data4.hexToInt{
            self.revolutionButton.setTitle(String(intData4), for: .normal)
            self.revolutionSelectIndex = self.revolutions.firstIndex(of: String(intData4)) ?? 0
        }
        
        if let intData5 = data5.hexToInt{
            self.alarmNameButton.setTitle(String(format: "%@", intData5 == 1 ? "ON" : "OFF"), for: .normal)
            self.alarmSelectIndex = intData5
        }
        
        if let intData6 = data6.hexToInt,let intData7 = data7.hexToInt{
            let time = String(format: "%d:%d", intData6,intData7)
            self.alarmHour = intData6
            self.alarmMinute = intData7
            self.alarmTimeButton.setTitle(time, for: .normal)
        }
        if let intData8 = data8.hexToInt{
            self.singleAlarmNameButton.setTitle(String(format: "%@", intData8 == 1 ? "ON" : "OFF"), for: .normal)
            self.singleAlarmSelectIndex = intData8
        }
  
        if let intData9 = data9.hexToInt,let intData10 = data10.hexToInt{
            let time = String(format: "%d:%d", intData9,intData10)
            self.singleAlarmHour = intData9
            self.singleAlarmMinute = intData10
            self.singleAlarmTimeButton.setTitle(time, for: .normal)
        }
        
        if  let intData11 = data11.hexToInt{
            self.utcIndex = intData11
            self.utcsButton.setTitle(self.UTCs[self.utcIndex], for: .normal)
        }
        if let intData12 = data12.hexToInt{
            self.displaymodeButton.setTitle(String(intData12), for: .normal)
            self.displayModeIndex = self.displayMode.firstIndex(of: String(intData12)) ?? 0
        }
        
        if let intData13 = data13.hexToInt{
            self.circleButton.setTitle(String(intData13), for: .normal)
            self.circleSelectIndex = self.circles.firstIndex(of: String(intData13)) ?? 0
        }
        
        if let intData14 = data14.hexToInt{
            self.rotationButton.setTitle(String(intData14), for: .normal)
            self.rotationSelectIndex =  self.rotations.firstIndex(of: String(intData14)) ?? 0
        }
    }
}
